#include "requestcodec.h"

RequestCodec::RequestCodec() : Codec()
{
}

RequestCodec::RequestCodec(RequestInfo *info) : Codec()
{
    initMessage(info);
}

RequestCodec::RequestCodec(QString msg) : Codec()
{
    initMessage(msg);
}

RequestCodec::~RequestCodec()
{

}

void RequestCodec::initMessage(RequestInfo *info)
{
    m_msg.set_cmdtype(info->cmdtype);
    m_msg.set_clientid(info->clientID.toStdString());
    m_msg.set_serverid(info->serverID.toStdString());
    m_msg.set_sign(info->sign.toStdString());
    m_msg.set_data(info->data.toStdString());
}

void RequestCodec::initMessage(QString msg)
{
    // base64 解码
    QByteArray array = QByteArray::fromBase64(msg.toUtf8());
    // 转换为string 类型
    m_encMsg = string(array.data(), array.size());
}

QString RequestCodec::encodeMsg()
{
    string output;
    m_msg.SerializeToString(&output);
    QByteArray data = QByteArray(output.data(), output.size()).toBase64();
    return data;
}

void RequestCodec::decodeMsg(void *output)
{
    m_msg.ParseFromString(m_encMsg);
    // 读出对象中的数据
    m_info.clientID = QString::fromStdString(m_msg.clientid());
    m_info.serverID = QString::fromStdString(m_msg.serverid());
    m_info.sign = QString::fromStdString(m_msg.sign());
    m_info.data = QString::fromStdString(m_msg.data());
    m_info.cmdtype = m_msg.cmdtype();
    // 数据传出, 赋值给传出参数
    *(RequestInfo*)output = m_info;
}
